#!/usr/bin/env python3
"""
任务 7: 集成组件到 main.py
文件: main.py (继续修改)
导入所有核心组件和模型
实现 create_config() 函数创建配置对象
实现 setup_components() 函数初始化组件
"""

import sys
import os
from pathlib import Path

# 导入我们创建的模块
try:
    from models.git_repository import GitRepository
    from models.configuration import Configuration
    from utils.directory_scanner import DirectoryScanner
    from utils.git_executor import GitExecutor
    from utils.result_reporter import ResultReporter
except ImportError as e:
    print(f"错误：无法导入模块: {e}")
    print("请确保所有模块文件都在正确的位置")
    sys.exit(1)

def create_config(args) -> Configuration:
    """
    创建配置对象
    
    Args:
        args: 命令行参数对象
        
    Returns:
        Configuration: 配置对象
    """
    try:
        config = Configuration(
            root_directory=args.directory,
            include_patterns=args.include,
            exclude_patterns=args.exclude,
            verbose=args.verbose,
            dry_run=args.dry_run,
            timeout=args.timeout,
            max_workers=args.max_workers
        )
        
        if not config.is_valid:
            print(f"配置错误: {config.error_message}")
            return None
            
        return config
        
    except Exception as e:
        print(f"创建配置时发生错误: {str(e)}")
        return None

def setup_components(config: Configuration) -> tuple:
    """
    设置和初始化组件
    
    Args:
        config: 配置对象
        
    Returns:
        tuple: (scanner, executor, reporter) 组件元组
    """
    try:
        # 创建目录扫描器
        scanner = DirectoryScanner(max_depth=10)
        
        # 创建 Git 执行器
        executor = GitExecutor(
            timeout=config.timeout,
            verbose=config.verbose
        )
        
        # 创建结果报告器
        reporter = ResultReporter(verbose=config.verbose)
        
        return scanner, executor, reporter
        
    except Exception as e:
        print(f"设置组件时发生错误: {str(e)}")
        return None, None, None

def test_integration():
    """测试组件集成"""
    print("测试组件集成...")
    
    # 模拟命令行参数
    class MockArgs:
        def __init__(self):
            self.directory = "."
            self.include = []
            self.exclude = ["*/.git", "*/venv", "*/node_modules"]
            self.verbose = True
            self.dry_run = False
            self.timeout = 300
            self.max_workers = 4
    
    args = MockArgs()
    
    # 测试配置创建
    print("测试配置创建...")
    config = create_config(args)
    if config:
        print(f"配置创建成功: {config.get_summary()}")
    else:
        print("配置创建失败")
        return
    
    # 测试组件设置
    print("测试组件设置...")
    scanner, executor, reporter = setup_components(config)
    
    if scanner and executor and reporter:
        print("组件设置成功")
        print(f"扫描器类型: {type(scanner)}")
        print(f"执行器类型: {type(executor)}")
        print(f"报告器类型: {type(reporter)}")
    else:
        print("组件设置失败")
        return
    
    # 测试基本功能
    print("测试基本功能...")
    
    # 测试目录扫描
    git_repos = scanner.find_git_repositories(
        config.root_directory,
        config.include_patterns,
        config.exclude_patterns
    )
    print(f"找到 {len(git_repos)} 个 Git 仓库")
    
    # 测试 Git 执行器
    if git_repos:
        repo_path = git_repos[0]
        print(f"测试 Git 执行器: {repo_path}")
        
        # 检查仓库有效性
        is_valid = scanner.is_valid_git_repo(repo_path)
        print(f"仓库 {repo_path} 是否有效: {is_valid}")
        
        if is_valid:
            # 测试状态检查
            success, stdout, stderr = executor.execute_git_command(repo_path, ["status"])
            print(f"状态检查结果: 成功={success}, 输出={stdout.strip()}")
    
    # 测试结果报告器
    print("测试结果报告器...")
    reporter.start_processing(3)
    
    # 模拟处理过程
    test_repos = ["/tmp/repo1", "/tmp/repo2", "/tmp/repo3"]
    for i, repo_path in enumerate(test_repos, 1):
        reporter.display_progress(repo_path, i, 3)
        
        # 模拟不同的结果
        if i == 1:
            reporter.log_result(repo_path, "success", "更新成功")
        elif i == 2:
            reporter.log_result(repo_path, "failed", "", "网络超时")
        else:
            reporter.log_result(repo_path, "skipped", "仓库不存在")
    
    reporter.print_summary()

if __name__ == "__main__":
    test_integration()